package cool.lichuan.project.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wf.captcha.utils.CaptchaUtil;
import cool.lichuan.common.constant.UserConstant;
import cool.lichuan.framework.config.AdminConfig;
import cool.lichuan.project.system.domain.User;
import cool.lichuan.project.system.dto.LoginDto;
import cool.lichuan.project.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lichuan
 * @date 2021/11/24 15:53
 * @description
 */
@Service
@RequiredArgsConstructor
public class LoginService {
    private final AdminConfig adminConfig;
    private final UserService userService;

    /**
     * 用户登录
     * @param loginDto 登录信息
     * @param request 请求
     */
    public void login(LoginDto loginDto, HttpServletRequest request) {
        this.checkCode(loginDto.getCode(), request);
        User user = this.checkUser(loginDto.getLoginName(), loginDto.getPassword());
        StpUtil.login(user.getUserId(), loginDto.getDevice());
    }

    /**
     * 校验验证码
     *
     * @param code 输入的验证码
     * @return 返回验证码校验结果
     */
    private void checkCode(String code, HttpServletRequest request) {
        if (adminConfig.getCaptchaEnabled()) {
            if (!CaptchaUtil.ver(code, request)) {
                CaptchaUtil.clear(request);
                throw new UtilException("验证码不正确");
            }
        }
    }

    /**
     * 校验登录用户名称和密码
     *
     * @param loginName 用户名
     * @param password  密码
     * @return 校验结果
     */
    private User checkUser(String loginName, String password) {
        User loginUser = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getLoginName, loginName), false);
        Assert.notNull(loginUser, UserConstant.ERROR_USER_OR_PASSWORD_TIPS);
        Assert.isTrue(loginUser.getPassword().equals(SaSecureUtil.md5BySalt(password, loginName)), UserConstant.ERROR_USER_OR_PASSWORD_TIPS);
        Assert.isTrue(UserConstant.USER_STATUS_OK.equals(loginUser.getUserStatus()), UserConstant.ERROR_USER_STATUS_TIPS);
        return loginUser;
    }
}
